/**
 * @file 音乐主题
 * @module music/service/music
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires axios - 网络请求库
 * @requires qs - 参数序列化
 * @requires music/config - 接口配置
 */
const axios = require('axios').default,
      qs = require('qs'),
      config = require('../config/config');

/**
 * @description 音乐主题列表
 * @param {string} field - 主题
 * @param {string} page - 页码（可选）
 * @param {string} limit - 条数（可选）
 * @returns {object} 
 */
const topic = async ({ field, page = 1, limit = 10 }) => {
  const { data } = await axios({
    method: 'GET',
    url: `${config.musicDomain}/top/playlist?${qs.stringify(Object.assign({
      order: 'hot',
      limit,
      cat: field,
      offset: (page - 1) * limit
    }))}`
  });

  let { code, playlists, cat, total } = data;

  // 数据过滤
  playlists = playlists.map(item => ({
    _id: item.id,
    title: item.name,
    coverImgUrl: item.coverImgUrl,
    desc: item.description
  }));

  if (code === 200) {
    return {
      code: 0,
      message: 'get topic list success.',
      data: {
        topic: cat,
        total,
        lists: playlists
      }
    }
  } else {
    return {
      code: -1,
      message: 'get topic list failed.',
      data: {}
    }
  }
}

/**
 * @description 音乐主题详情列表
 * @param {string} id - 主题ID
 * @param {number} limit - 条数限制
 * @returns {object} 
 */
const list = async ({ id, limit = 50 }) => {
  try {
    const { data } = await axios({
      method: 'GET',
      url: `${config.musicDomain}/playlist/detail?${qs.stringify({ id })}`
    });

    let { code, playlist } = data;
  
    if (code === 200) {
      const ids = playlist.trackIds.map(item => item.id);
      const { name, description: desc, coverImgUrl, tags } = playlist;
  
      const { data } = await axios({
        method: 'GET',
        url: `${config.musicDomain}/song/detail?${qs.stringify({ ids: ids.join(',') })}`
      });
  
      let { code, songs } = data;
  
      if (code === 200) {
        // 数据过滤
        songs = songs.slice(0, limit).map(item => ({
          id: item.id,
          name: item.name.replace(/\（.*\）/g, '').replace(/\(.*\)/g, ''),
          author: item.ar.map(item => item.name).join(' '),
          url: item.al.picUrl,
          dt: item.dt
        }));
  
        return {
          code: 0,
          message: 'get topic detail list success.',
          data: {
            title: name,
            desc: desc.replace(/\n/g, ''),
            coverImgUrl,
            tags: tags.join(' '),
            lists: songs
          }
        }
      } else {
        return {
          code: -1,
          message: 'get topic detail list failed.',
          data: {}
        }
      }
    } else {
      return {
        code: -1,
        message: 'get topic detail list failed.',
        data: {}
      }
    }
  } catch (error) {
    console.log('[error]：', error);
    return {
      code: -1,
      message: error,
      data: {}
    }
  }
}

/**
 * @description 音乐播放路径
 * @param {number} id - 音频ID
 * @returns {object} 
 */
const url = async ({ id }) => {
  const { data } = await axios({
    method: 'GET',
    url: `${config.musicDomain}/song/url?${qs.stringify({ id })}`
  });
  const { code } = data;

  if (code === 200) {
    const { data: [ { url } ] } = data;
    
    return {
      code: 0,
      message: 'get music url success.',
      data: {
        url
      }
    }
  } else {
    return {
      code: -1,
      message: 'get music url failed.',
      data: {}
    }
  }
}

module.exports = {
  topic,
  list,
  url
}